<template>
  <a-modal
    :title="title"
    :width="500"
    :visible="visible"
    :closable="false"
    :maskClosable="false">

    <template slot="footer">
      <a-button type="primary" @click="selectOk">确认</a-button>
    </template>

    <a-form-model>
      <a-form-model-item v-if="isMultiTenant" :labelCol="{span:4}" :wrapperCol="{span:20}" style="margin-bottom:10px" :validate-status="validate_status1">
        <a-tooltip placement="topLeft" >
          <template slot="title">
            <span>您有多个租户，请选择登录租户</span>
          </template>
          <a-avatar style="backgroundColor:#87d068" icon="gold" />
        </a-tooltip>

        <a-select @change="handleTenantChange" :class="{'valid-error':validate_status1=='error'}" placeholder="请选择登录租户" style="margin-left:10px;width: 70%">
          <a-icon slot="suffixIcon" type="gold" />
          <a-select-option v-for="d in tenantList" :key="d.id" :value="d.id">
            {{ d.name }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item v-if="isMultiDepart" :labelCol="{span:4}" :wrapperCol="{span:20}" style="margin-bottom:10px" :validate-status="validate_status2">
        <a-tooltip placement="topLeft" >
          <template slot="title">
            <span>您有多个部门，请选择登录部门</span>
          </template>
          <div class="lableText">部门</div> 
          <a-avatar style="backgroundColor:rgb(112,182,3);" icon="gold" />
        </a-tooltip>

        <a-select @change="handleDepartChange" :class="{'valid-error':validate_status2=='error'}" placeholder="请选择登录部门" style="margin-left:10px;width: 70%">
          <a-icon slot="suffixIcon" type="gold" />
          <a-select-option v-for="d in departList" :key="d.id" :value="d.orgCode">
            {{ d.departName }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <!-- 结算组织Form -->
      <a-form-model-item v-if="isMultiAccounts" :labelCol="{span:4}" :wrapperCol="{span:20}" style="margin-bottom:10px" :validate-status="validate_status3">
        <a-tooltip placement="topLeft" >
          <template slot="title">
            <span>您有多个结算组织，请选择结算组织</span>
          </template>
          <div class="lableText">结算组织</div> 
          <a-avatar style="backgroundColor:rgb(2,167,240);" icon="gold" />
        </a-tooltip>

        <a-select @change="handleAccountChange" :class="{'valid-error':validate_status3=='error'}" placeholder="请选择结算组织" style="margin-left:10px;width: 70%">
          <a-icon slot="suffixIcon" type="gold" />
          <a-select-option v-for="a in accountsList" :key="a.id" :value="a.settlement_org_id">
            {{ a.settlement_org_name }}
          </a-select-option>
        </a-select>
      </a-form-model-item>

    </a-form-model>
  </a-modal>
</template>

<script>

import Vue from 'vue'
import { putAction } from '@/api/manage'
import { USER_INFO } from '@/store/mutation-types'

export default {
    name: 'LoginSelectTenant',
    data(){
      return {
        visible: false,
        isMultiDepart:false,
        departList:[],
        isMultiAccounts:false,
        accountsList:[], //结算组织 
        isMultiTenant:false,
        tenantList:[],

        username:'',
        orgCode:'',
        tenant_id:'',
        settlement_org_id:'', //结算组织id
        validate_status1: "",
        validate_status2: "",
        validate_status3:'',
      }
    },
    computed:{
       title(){
        if(this.isMultiDepart && this.isMultiTenant){
          return '请选择租户和部门'
        }else if(this.isMultiDepart && !this.isMultiTenant){
          return '请选择部门'
        }else if(!this.isMultiDepart && this.isMultiTenant){
          return '请选择租户'
        }else if(this.isMultiDepart || this.isMultiAccounts){
          return '请选择'
        }
      }
    },
    methods:{
      clear(){
        this.departList = []
        this.tenantList = []
        this.accountsList=[]
        this.visible=false
        this.validate_status1=''
        this.validate_status2=''
        this.validate_status3=''
      },
      bizDepart(loginResult){
        let multi_depart = loginResult.multi_depart               
        //0:无部门 1:一个部门 2:多个部门
        if(multi_depart==0){
          //  this.$notification.warn({
          //    message: '提示',
          //    description: `您尚未归属部门,请确认账号信息`,
          //    duration:3
          //  });
          this.isMultiDepart = false
        }else if(multi_depart==2){
          this.visible=true
          this.isMultiDepart = true
          this.departList = loginResult.departs
        }else {
          //只有一个部门时
          if(multi_depart==1 && loginResult.departs.length==1){
             this.orgCode=loginResult.departs[0].orgCode
          }      
          this.isMultiDepart = false
        }
      },
      //结算组织
      bizAccount(loginResult){                     
        let multi_accounts = loginResult.multi_accounts
        //0:无结算组织 1:一个结算组织 2:多个结算组织
        if(multi_accounts==0){
          //  this.$notification.warn({
          //    message: '提示',
          //    description: `您尚未结算组织,请确认账号信息`,
          //    duration:3
          //  }); 
          this.isMultiAccounts=false
        }else if(multi_accounts==2){
          this.visible=true
          this.isMultiAccounts = true
          this.accountsList=loginResult.accounts
        }else {
          //只有一个结算组织
          if(multi_accounts==1 && loginResult.accounts.length==1){
             this.settlement_org_id=loginResult.accounts[0].settlement_org_id
          } 
          this.isMultiAccounts = false
        } 

      },
      bizTenantList(loginResult) {
        let tenantList = loginResult.tenantList
        if (Array.isArray(tenantList)) {
          if (tenantList.length === 0) {
            this.isMultiTenant = false
          } else if (tenantList.length === 1) {
            this.tenant_id = tenantList[0].id
            this.isMultiTenant = false
          } else {
            this.visible = true
            this.isMultiTenant = true
            this.tenantList = tenantList
          }
        }
      },
      show(loginResult){       
        this.clear();
        this.bizDepart(loginResult);
        this.bizAccount(loginResult)
        let user = Vue.ls.get(USER_INFO)
        this.username = user.username
        this.bizTenantList(loginResult);

        if(this.visible===false){
          this.$store.dispatch('saveTenant', this.tenant_id);
          this.$emit('success')
        }

      },
      closeModal(){
         this.clear();
         this.visible = false
      },
      requestFailed (err) {
        this.$notification[ 'error' ]({
          message: '登录失败',
          description: ((err.response || {}).data || {}).message || err.message || "请求出现错误，请稍后再试",
          duration: 4,
        });
        this.loginBtn = false;
      },
      departResolve(){
        return new Promise((resolve, reject)=>{
          if(this.isMultiDepart===false && this.isMultiAccounts===false){
            resolve();
          }else{
            let obj = {
              orgCode:this.orgCode,
              accountId:this.settlement_org_id,
              username:this.username
            }
            putAction("/sys/selectDepart",obj).then(res=>{
              if(res.success){               
                const userInfo = res.result.userInfo;               
                Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000);
                this.$store.commit('SET_INFO', userInfo);
                //console.log("---切换组织机构---userInfo-------",store.getters.userInfo.orgCode);
                resolve();
              }else{               
                this.requestFailed(res)
                this.$store.dispatch('Logout');
                reject();
              }
            })
          }
        })
      },
      selectOk(){
        if(this.isMultiTenant && !this.tenant_id){
          this.validate_status1='error'
          return false
        }
        if(this.isMultiDepart && !this.orgCode){
          this.validate_status2='error'
          return false
        }
        if(this.isMultiAccounts && !this.settlement_org_id){
          this.validate_status3='error'
          return false
        }   
        this.departResolve().then(()=>{         
          this.$store.dispatch('saveTenant', this.tenant_id);
          if(this.isMultiTenant){
            this.$emit('success')
          }else{
            this.$emit('success')
          }
        }).catch(()=>{
          console.log('登录选择出问题')
        })
      },
      handleTenantChange(e){
        this.validate_status1 = ''
        this.tenant_id = e
      },
      handleDepartChange(e){
        this.validate_status2 = ''
        this.orgCode = e
      },
      //选择结算组织
      handleAccountChange(e){
        this.validate_status3=''
        this.settlement_org_id=e
      },
    }
  }
</script>

<style scoped>
.lableText{
  display: inline-block;
  width: 60px;
  text-align: right;
  margin-right: 10px;
}
</style>